package udp_syslog;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import org.apache.log4j.Logger;

import util.MyLog;

public class MyUdpClient {
	// 瀹氫箟鍙戦�佹暟鎹姤鐨勭洰鐨勫湴
	public static final int DEST_PORT = 30000;
	//public static final String DEST_IP = "127.0.0.1";
	public static final String DEST_IP = "192.168.1.221";
	// 瀹氫箟姣忎釜鏁版嵁鎶ョ殑鏈�澶уぇ灏忎负4K
	private static final int DATA_LEN = 4*1024;
	// 瀹氫箟璇ュ鎴风浣跨敤鐨凞atagramSocket
	private DatagramSocket socket = null;
	// 瀹氫箟鎺ユ敹缃戠粶鏁版嵁鐨勫瓧鑺傛暟缁�
	byte[] inBuff = new byte[DATA_LEN];
	// 浠ユ寚瀹氬瓧鑺傛暟缁勫垱寤哄噯澶囨帴鍙楁暟鎹殑DatagramPacket瀵硅薄
	private DatagramPacket inPacket;
	private static int count = 0;

	private Logger recLog = MyLog.getInstance().getReceiveLog();

	public void init() throws IOException {
		try {
			// 鍒涘缓涓�涓鎴风DatagramSocket锛屼娇鐢ㄩ殢鏈虹鍙�
			socket = new DatagramSocket(DEST_PORT);
			socket.setReceiveBufferSize(100*1024);
			inPacket = new DatagramPacket(inBuff, inBuff.length,
					InetAddress.getByName(DEST_IP), DEST_PORT);
			//inPacket = new DatagramPacket(inBuff, inBuff.length);
			while (true) {
				try {
					//inBuff = new byte[DATA_LEN];
					//inPacket = new DatagramPacket(inBuff, inBuff.length,
					//		InetAddress.getByName(DEST_IP), DEST_PORT);
					count++;
					// 璇诲彇Socket涓殑鏁版嵁锛岃鍒扮殑鏁版嵁鏀惧湪inPacket鎵�灏佽鐨勫瓧鑺傛暟缁勯噷銆�
					socket.receive(inPacket);
					String rec = new String(inBuff, 0, inPacket.getLength());
					recLog.info(count + "<->" + rec);
					//Thread.sleep(10);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
			//for (int j = 1; j <= 1 ; j++) {
			//	new RecDateClient(j).start();
			//}
		}
		// 浣跨敤finally鍧椾繚璇佸叧闂祫婧�
		finally {
			if (socket != null) {
				//socket.close();
			}
		}
	}

	public static void main(String[] args) throws IOException {
		new MyUdpClient().init();
	}
	
	/*
	private void process(int index) {
		while (true) {
			try {
				//inBuff = new byte[DATA_LEN];
				//inPacket = new DatagramPacket(inBuff, inBuff.length,
				//		InetAddress.getByName(DEST_IP), DEST_PORT);
				count++;
				// 璇诲彇Socket涓殑鏁版嵁锛岃鍒扮殑鏁版嵁鏀惧湪inPacket鎵�灏佽鐨勫瓧鑺傛暟缁勯噷銆�
				socket.receive(inPacket);
				String rec = new String(inBuff, 0, inPacket.getLength());
				recLog.info("(" + index + ") " + count + "<->" + rec);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	}

	
    private class RecDateClient extends Thread {
    	
    	private int index;
    	
    	public RecDateClient(int index) {
    		this.index = index;
    	}
    	
    	public void run(){
    		recLog.info("鍚姩澶勭悊绾跨▼(" + index + ")");
    		process(index);
    		recLog.info("(old)澶勭悊绾跨▼(" + index + ")鍏抽棴锛侊紒锛�");
		}
    }
    */
}
